<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="用户单位" prop="deptId">-->
<!--        <el-input-->
<!--          v-model="queryParams.deptId"-->
<!--          placeholder="请输入用户单位id"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->

      <!-- 单位编号 -->
      <el-form-item label="用户单位" prop="deptId">
        <treeselect
          ref="deptSelect"
          v-model="queryParams.deptId"
          :options="enabledDeptOptions"
          :show-count="true"
          placeholder="请选择用户单位"
          style="width: 205px"
          @input="handleDeptSelect"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="姓名" prop="nickName">
        <el-input
          v-model="queryParams.nickName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="身份证号" prop="idcard">
        <el-input
          v-model="queryParams.idcard"
          placeholder="请输入身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="批次编号" prop="batchNumber">
        <el-input
          v-model="queryParams.batchNumber"
          placeholder="请输入批次编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="岗位编号" prop="positionCode">
        <el-input
          v-model="queryParams.positionCode"
          placeholder="请输入岗位编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="公司名" prop="companyName">
        <el-input
          v-model="queryParams.companyName"
          placeholder="请输入公司名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="岗位名称" prop="positionName">
        <el-input
          v-model="queryParams.positionName"
          placeholder="请输入岗位名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="工作地点" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入工作地点"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核情况" prop="statusApply">
        <el-select
          v-model="queryParams.statusApply"
          placeholder="请选择审核情况"
          clearable    style="width: 100%"
        >
          <el-option label="未审查" :value="0" />
          <el-option label="审核通过" :value="1" />
          <el-option label="未通过" :value="2" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:apply:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:apply:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:apply:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:apply:export']"
        >导出</el-button>
      </el-col>
      <!-- 新增导出所有报名数据按钮 -->
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExportAllData"
        >导出所有报名数据</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="applyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="报名顺序" align="center" prop="applyId" />-->
<!--      <el-table-column label="报名用户id" align="center" prop="userId" />-->
      <el-table-column label="用户单位编号" align="center" prop="deptId" />
      <el-table-column label="姓名" align="center" prop="nickName" />
      <el-table-column label="用户身份证号" align="center" prop="idcard" />
      <el-table-column label="批次编号" align="center" prop="batchNumber" />
      <el-table-column label="岗位编号" align="center" prop="positionCode" />
      <el-table-column label="公司名" align="center" prop="companyName" />
      <el-table-column label="岗位名称" align="center" prop="positionName" />
      <el-table-column label="工作地点" align="center" prop="location" />
      <el-table-column label="审核情况" align="center">
        <template slot-scope="scope">
          {{ formatStatusApply(scope.row.statusApply) }}
        </template>
      </el-table-column><!--      <el-table-column label="流程id" align="center" prop="processId" />-->
      <el-table-column label="退回原因" align="center" prop="returnReason" />
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:apply:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:apply:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[10, 20, 30, 50, 100,10000]"
      @pagination="getList"
    />

    <!-- 添加或修改报名管理信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="用户单位" prop="deptId">
          <treeselect v-model="form.deptId" :options="enabledDeptOptions" :show-count="true" placeholder="请选择归属部门" style="width: 250px;"/>
        </el-form-item>
        <el-form-item label="用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户姓名" />
        </el-form-item>
        <el-form-item label="姓名" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="身份证号" prop="idcard">
          <el-input v-model="form.idcard" placeholder="请输入用户身份证号" />
        </el-form-item>
        <el-form-item label="批次编号" prop="batchNumber">
          <el-input v-model="form.batchNumber" placeholder="请输入批次编号" />
        </el-form-item>
        <el-form-item label="岗位编号" prop="positionCode">
          <el-input v-model="form.positionCode" placeholder="请输入岗位编号" />
        </el-form-item>
        <el-form-item label="公司名" prop="companyName">
          <el-input v-model="form.companyName" placeholder="请输入公司名" />
        </el-form-item>
        <el-form-item label="岗位名称" prop="positionName">
          <el-input v-model="form.positionName" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="工作地点" prop="location">
          <el-input v-model="form.location" placeholder="请输入工作地点" />
        </el-form-item>
        <el-form-item label="审核情况" prop="statusApply">
          <el-input v-model="statusApplyText" placeholder="请输入审核情况" />
        </el-form-item>
        <el-form-item label="退回原因" prop="returnReason">
          <el-input v-model="form.returnReason" placeholder="请输入退回原因" />
        </el-form-item>
        <el-form-item label="创建时间" prop="createTime">
        <el-input v-model="form.createTime" placeholder="请输入退回原因" />
      </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listApply, getApply, delApply, addApply, updateApply, exportAllApplyData} from "@/api/system/apply";
import Treeselect from "@riophae/vue-treeselect";
import {deptTreeSelect} from "@/api/system/user";
import dict from "@/utils/dict";
import {getUser, getUserProfile} from "@/api/system/user";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Apply",
  components: {Treeselect},
  data() {
    return {
      // 所有部门树选项
      deptOptions: undefined,
      // 过滤掉已禁用部门树选项
      enabledDeptOptions: [],
      // 保存选中的部门标签
      selectedDeptLabel: '',
      //导出文件名
      fileName: '',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报名管理信息表格数据
      applyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userId: null,
        deptId: null,
        deptName: null,
        userName: null,
        nickName: null,
        idcard: null,
        batchNumber: null,
        positionCode: null,
        companyName: null,
        positionName: null,
        location: null,
        statusApply: null,
        processId: null,
        returnReason: null,
        createTime: null,
        remark: null
      },
      // 表单参数
      form: {},
      userForm: {
        userName: '',
        phonenumber: '',
        email: '',
        sex: '',
        status: '',
        userId:'',
        deptId: '',
            },
      // 表单校验
      rules: {
        userId: [
          { required: true, message: "报名用户id不能为空", trigger: "blur" }
        ],
        deptId: [
          { required: true, message: "用户单位id不能为空", trigger: "blur" }
        ],
        userName: [
          { required: true, message: "用户姓名不能为空", trigger: "blur" }
        ],
        nickName: [
          { required: true, message: "姓名不能为空", trigger: "blur" }
        ],
        idcard: [
          { required: true, message: "用户身份证号不能为空", trigger: "blur" }
        ],
        positionCode: [
          { required: true, message: "岗位编号不能为空", trigger: "blur" }
        ],
        companyName: [
          { required: true, message: "公司名不能为空", trigger: "blur" }
        ],
        positionName: [
          { required: true, message: "岗位名称不能为空", trigger: "blur" }
        ],
        location: [
          { required: true, message: "工作地点不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getUserInfo();



  },
  computed: {
    statusApplyText() {
      switch (this.form.statusApply) {
        case 0:
          return '未审查';
        case 1:
          return '审核通过';
        case 2:
          return '未通过';
        default:
          return '未知状态';
      }
    }
  },
  methods: {
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data;
        const filteredDepts = this.filterDisabledDept(JSON.parse(JSON.stringify(response.data)));
        if (this.userForm.deptId===100){
          // 作为平级选项添加"全部数据"
          this.enabledDeptOptions = [
            { id: '', label: '全部数据' },
            ...filteredDepts
          ];
        }else {
          this.enabledDeptOptions = [
            ...filteredDepts
          ];

        }
      });
    },
    // 过滤禁用的部门
    filterDisabledDept(deptList) {
      return deptList.filter(dept => {
        if (dept.disabled) {
          return false;
        }
        if (dept.children && dept.children.length) {
          dept.children = this.filterDisabledDept(dept.children);
        }
        return true;
      });
    },
    // 获取用户信息
    getUserInfo() {
      getUserProfile().then(response => {
        this.userForm = response.data;
        // 获取用户信息后，设置查询参数中的userId并重新加载列表
        if (response.data.deptId) {
          this.queryParams.deptId = response.data.deptId;
          // 如果是首次加载，需要调用getList
          if (this.applyList.length === 0) {
            this.getList();
          }
        }
        this.getDeptTree();
      }).catch(error => {
        console.error('获取用户信息失败:', error);
      });
    },

    /** 查询报名管理信息列表 */
    getList() {
      this.loading = true;
      listApply(this.queryParams).then(response => {
        this.applyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        applyId: null,
        userId: null,
        deptId: null,
        userName: null,
        nickName: null,
        idcard: null,
        batchNumber: null,
        positionCode: null,
        companyName: null,
        positionName: null,
        location: null,
        statusApply: null,
        processId: null,
        returnReason: null,
        createBy: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
       if (this.queryParams.deptId === null||this.queryParams.deptId === undefined) {
            this.queryParams.deptId=this.userForm.deptId;
        }
      this.getList();
      this.fileName=this.selectedDeptLabel;
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.applyId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加报名管理信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const applyId = row.applyId || this.ids
      getApply(applyId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改报名管理信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.applyId != null) {
            updateApply(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addApply(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const applyIds = row.applyId || this.ids;
      this.$modal.confirm('是否确认删除报名管理信息编号为"' + applyIds + '"的数据项？').then(function() {
        return delApply(applyIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleDeptSelect(value) {
        // 当选择改变时，查找并保存选中的文本
        if (value) {
          const findDeptText = (deptList, val) => {
            for (let dept of deptList) {
              if (dept.id === val) {
                return dept.label;
              }
              if (dept.children && dept.children.length) {
                const found = findDeptText(dept.children, val);
                if (found) return found;
              }
            }
            return '';
          };

          this.selectedDeptLabel = findDeptText(this.enabledDeptOptions, value);
        } else {
          this.selectedDeptLabel = '全部数据';
        }
      },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/apply/export', {
        ...this.queryParams
      }, `apply_${new Date().getTime()}.xlsx`)
    },

    /** 新增：导出所有报名数据 */
    // 新增：导出所有报名数据
    handleExportAllData() {
      let filename = this.fileName;
      filename += `_报名数据`;
      this.download('system/apply/export/all', {
        ...this.queryParams
      }, `${filename}_${new Date().getTime()}.xlsx`)

    },


    /** 申请状态属性显示 */
    formatStatusApply(status) {
      switch (status) {
        case 0:
          return '未审查';
        case 1:
          return '审核通过';
        case 2:
          return '未通过';
        default:
          return '未知状态';
      }
    },
  }
};
</script>
